package es.us.mwm.managers.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Clase filter para evitar el acceso directo por URL a determinadas paginas de la aplicacion
 * Filtro especifico para las partes que puede acceder un usuario. Alertas
 * @author y0rg
 */
public class LoginFilter implements Filter {

    /**
     * Constructor basico por defecto
     */
    public LoginFilter() {

    }

    /**
     * Checks if user is logged in. If not it redirects to the index.xhtml page.
     * @param request
     * @param response
     * @param chain
     * @throws java.io.IOException
     * @throws javax.servlet.ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Get the loginBean from session attribute
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(false);
        // For the first application request there is no loginBean in the session so user needs to log in
        // For other requests loginBean is present but we need to check if user has logged in successfully
        if (session == null || session.getAttribute("user")==null) { 
        //No compruebo si estas como admin, lo dejo en plan backdoor
            
            String contextPath = ((HttpServletRequest) request).getContextPath();
            ((HttpServletResponse) response).sendRedirect(contextPath + "/faces/index.xhtml");
        } else {
            //System.out.println("USUARIO->" + session.getAttribute("user"));
        }
        chain.doFilter(request, response);
    }

    /**
     * Se inicializa el filtro al iniciar la aplicaciones
     * @param config
     * @throws ServletException
     */
    public void init(FilterConfig config) throws ServletException {
        // Nothing to do here!
    }

    /**
     * Metodo que se ejecutara al finalizar la aplicaciones
     */
    public void destroy() {
        // Nothing to do here!
    }

}
